package com.vader.BIO;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

/**
 * @author kaivader
 */
public class BIOServer {
    public static void main(String[] args) throws IOException {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 3, 60,
                TimeUnit.SECONDS, new ArrayBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());

        ServerSocket socket = new ServerSocket(6666);

        System.out.println("客户端启动");

        while (true) {
            final Socket accept = socket.accept();
            System.out.println("连接到客户端");

            //单线程阻塞id
//            handler(accept);

//            多线程阻塞io
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    handler(accept);
                }
            });

        }
    }

    private static void handler(Socket socket) {


        try {
            byte[] bytes = new byte[1024];
            InputStream inputStream = socket.getInputStream();

            System.out.println(Thread.currentThread().getName());
            while (true) {
                int read = inputStream.read(bytes);
                if (read != -1) {
                    System.out.println(Thread.currentThread().getName());
                    String str = new String(bytes, 0, read);
                    System.out.println(str);
                } else {
                    System.out.println("🐟客户端断开连接");
                    break;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
